package com.mbengue.corp.apr.ra.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.context.FacesContext;

import com.mbengue.corp.apr.ra.core.Adresse;
import com.mbengue.corp.apr.ra.core.Evenement;
import com.mbengue.corp.apr.ra.dao.DAOFactory;
import com.mbengue.corp.apr.ra.dao.EvenementDao;
import com.mbengue.corp.apr.ra.dao.impl.LieuEvenementDaoImpl;

@ManagedBean(name = "calendarBean")
@SessionScoped
public class CalendrierBean implements Serializable {
  private static final long serialVersionUID = 1L;
  private Date debut;
  private Date fin;
  private List<Evenement> evenements;
  private EvenementDao evenementDao;
  private HtmlOutputText text;

  public CalendrierBean() {
    Calendar cal = new GregorianCalendar();
    cal.setTime(new Date());
    cal.add(GregorianCalendar.DATE, -7);
    debut = cal.getTime();
    cal.add(GregorianCalendar.MONTH, 1);
    fin = cal.getTime();
    evenementDao = DAOFactory.getEvenementDao();
    initializeEvents();
  }

  public Date getDebut() {
    return debut;
  }

  public void setDebut(Date aDebut) {
    debut = aDebut;
  }

  public Date getFin() {
    return fin;
  }

  public void setFin(Date aFin) {
    fin = aFin;
  }

  public List<Evenement> getEvenements() {
    return evenements;
  }

  public void initializeEvents() {
    evenements = new ArrayList<Evenement>();
    if (debut == null || fin == null) {
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "La date de début et/ou de fin est obligatoire", ""));
    }
    if (debut.after(fin)) {
      FacesContext.getCurrentInstance().addMessage(null,
          new FacesMessage(FacesMessage.SEVERITY_ERROR, "La date de fin doit être plus récents que celle de fin.", ""));
    }
    evenements = evenementDao.trouverEvenementParDates(debut, fin);
  }

  public Adresse getLieu() {
    Long idEvent = (Long) text.getAttributes().get("event");
    Evenement evenement = evenementDao.trouver(idEvent);
    return new LieuEvenementDaoImpl().trouverLieuEvenement(evenement).getAdresse();
  }

  public HtmlOutputText getText() {
    return text;
  }

  public void setText(HtmlOutputText text) {
    this.text = text;
  }
}
